<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use HasFactory;

    protected $fillable = [
        'content',
        'video_id',
        'user_id',
        'parent_id',
        'likes',
        'is_approved'
    ];

    protected $casts = [
        'is_approved' => 'boolean',
        'likes' => 'integer'
    ];

    // 关联视频
    public function video()
    {
        return $this->belongsTo(Video::class);
    }

    // 关联用户
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // 关联父评论
    public function parent()
    {
        return $this->belongsTo(Comment::class, 'parent_id');
    }

    // 关联子评论
    public function replies()
    {
        return $this->hasMany(Comment::class, 'parent_id');
    }

    // 作用域：只获取已审核的评论
    public function scopeApproved($query)
    {
        return $query->where('is_approved', true);
    }

    // 作用域：按时间排序
    public function scopeLatest($query)
    {
        return $query->orderBy('created_at', 'desc');
    }
}
